package com.dengxian.usercenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dengxian.usercenter.mapper.ImMapper;
import com.dengxian.usercenter.model.VO.UserVO;
import com.dengxian.usercenter.model.domain.Im;
import com.dengxian.usercenter.model.domain.User;
import com.dengxian.usercenter.service.ImService;
import com.dengxian.usercenter.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* @author 86151
* @description 针对表【im】的数据库操作Service实现
* @createDate 2023-03-21 22:43:49
*/
@Service
public class ImServiceImpl extends ServiceImpl<ImMapper, Im>
    implements ImService{

    @Resource
    private UserService userService;

    /**
     * 获取与登录用户有聊天记录用户列表
     * @param loginUser
     * @return
     */
    @Override
    public List<UserVO> listUsers(User loginUser) {
        //获得给当前登录用户发送过消息的用户列表
        QueryWrapper<Im> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("toId", loginUser.getId());
        List<Im> allUserList = this.list(queryWrapper);
        // 取出不重复的用户 uid
        Map<Long, List<Im>> listMap = allUserList.stream()
                .collect(Collectors.groupingBy(Im::getUid));
        List<Long> uIdList = new ArrayList<>(listMap.keySet());
        //在用户表中根据uidList返回聊天用户列表
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.in("id", uIdList);
        List<User> userList = userService.list(userQueryWrapper);
        //返回给前端的用户列表
        List<UserVO> userVoList = new ArrayList<>();
        for(User user : userList) {
            //类型强转，将user的属性给userVO
            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(user, userVO);
            userVoList.add(userVO);
        }
        return userVoList;
    }

//    /**
//     * 获取当前登录用户与某个用户的聊天记录
//     * @param messagesUserRequest
//     * @param loginUser
//     * @return
//     */
//    @Override
//    public List<Im> userMessagesList(MessagesUserRequest messagesUserRequest, User loginUser) {
//        //
//    }
}




